<?php
declare(strict_types=1);
namespace App\Console\Commands;

use Illuminate\Console\Command;
use Swoole\Coroutine;
use Swoole\Runtime;
use Swoole\Database\PDOConfig;
use Swoole\Database\PDOPool;
const N = 1024;
class Pool extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'make:pool';
    //protected $n = 1024;

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        Runtime::enableCoroutine();
        $s = microtime(true);

        Coroutine\run(function (){
            $pool = new PDOPool((new PDOConfig)
                ->withHost("127.0.0.1")
                ->withPort(3306)
                ->withDbName('allprint')
                ->withCharset('utf8mb4')
                ->withUsername('root')
                ->withPassword('talent003')
            );
            for ($n = N; $n--;) {
                Coroutine::create(function () use ($pool) {
                    $pdo = $pool->get();
                    $statement = $pdo->prepare('SELECT ? + ?');
                    if (!$statement) {
                        throw new RuntimeException('Prepare failed');
                    }
                    $a = mt_rand(1, 100);
                    $b = mt_rand(1, 100);
                    $result = $statement->execute([$a, $b]);
                    if (!$result) {
                        throw new RuntimeException('Execute failed');
                    }
                    $result = $statement->fetchAll();
                    var_dump($result);
                    if ($a + $b !== (int)$result[0][0]) {
                        throw new RuntimeException('Bad result');
                    }
                    $pool->put($pdo);
                });
            }
        });
        $s = microtime(true) - $s;
        echo 'Use ' . $s . 's for ' . N . ' queries' . PHP_EOL;

    }


}

